<template>
  <div>
    <!-- 获取激活码 -->
    <el-form
      :model="addForm"
      ref="addFormRef"
      label-position="top"
      :rules="rules"
    >
      <el-form-item label="设备编码" prop="outCode">
        <el-alert type="primary" :closable="false" class="py-[0.1rem]">
          {{ addForm.outCode ? addForm.outCode : "请输入设备编码" }}
        </el-alert>
      </el-form-item>

      <el-form-item label="国家" prop="countryId">
        <el-select
          v-model="addForm.countryId"
          placeholder="请选择国家"
          filterable
        >
          <el-option
            v-for="item in countryList"
            :key="item.id"
            :label="item.name + '__' + item.enName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <div class="fixed bottom-2 right-2">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading"
        >提交</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { handleApiResponse } from "@/utils/request.js";
import {
  GetCountryList,
  DeviceRegister,
} from "../../../../../wailsjs/go/api/DeviceApi";

onMounted(() => {
  selectCountryList();
  addForm.value.outCode = props.detailForm.outCode;
  addForm.value.productId = props.detailForm.typeId;
});

const emit = defineEmits(["handleClose", "handleCancel"]);
const props = defineProps({
  detailForm: {
    type: Object,
    default: () => {},
  },
});

const addFormRef = ref(null);
const addForm = ref({
  outCode: "",
  productId: null,
  deviceRegistBy: 2,
  countryId: null,
});

const loading = ref(false);
const handleSubmit = () => {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    loading.value = true;
    // 调用接口
    handleApiResponse(() => DeviceRegister(addForm.value)).then((res) => {
      if (res.code == 0) {
        sessionStorage.setItem(
          props.detailForm.outCode,
          JSON.stringify({ ...res.data, ...addForm.value, ...props.detailForm })
        );
        handleClose(res.data);
      }
      loading.value = false;
    });
  });
};

const handleClose = (data) => {
  addFormRef.value.resetFields();
  loading.value = false;
  emit("handleClose", { ...data, ...addForm.value, ...props.detailForm });
};

const handleCancel = () => {
  emit("handleCancel");
};

const countryList = ref([]); // 国家列表
async function selectCountryList() {
  handleApiResponse(() => GetCountryList()).then((res) => {
    if (res.code == 0) {
      countryList.value = res.data.countryList || [];
    }
  });
}

const rules = ref({
  outCode: [{ required: true, message: "请输入设备编码", trigger: "blur" }],
  productId: [{ required: true, message: "请选择产品", trigger: "blur" }],
  countryId: [{ required: true, message: "请选择国家", trigger: "blur" }],
});
</script>

<style scoped lang="scss">
</style>